import wsgiref.handlers
from google.appengine.ext import webapp
from google.appengine.api import mail
from django.core import validators

import RegistrationRecord
import EventRecord

class RegisterEvent( webapp.RequestHandler ):

  def post( self ):
    self.response.headers['Content-Type'] = 'text/html'

    id = self.request.get('id')
    name = self.request.get('name')
    email = self.request.get('email')

    if not name or not email:
      self.response.out.write('Fill in all the details to register.')
      return
    try:
      validators.isValidEmail(email,None)
    except validators.ValidationError:
      self.response.out.write('Use valid email address.')
      return

    record = RegistrationRecord.RegistrationRecord()
    record.id = id
    record.name = name
    record.email = email

    record.put()

    event_record = EventRecord.EventRecord \
      .gql( 'WHERE id = :1', id ) \
      .get()

    filling =  {
        'title' : event_record.title
      , 'date' : event_record.date
      , 'time' : event_record.time
      , 'venue' : event_record.venue
    }

    self.response.out.write(
'''
<p>
  Great! You have just registered to the event.<br />
  Title - %(title)s<br />
  Date - %(date)s<br />
  Time - %(time)s<br />
  Venue - %(venue)s<br />
</p>
''' % filling )

    mail.send_mail(
      sender = "misc.app@gmail.com",
      to = record.email,
      subject = "[Misc-App] Event Registration",
      body =
'''
Hi,

You have registered to the event.
  Title - %(title)s
  Date - %(date)s
  Time - %(time)s
  Venue - %(venue)s

--
Misc-App Collection.
''' % filling )
  # end of RegisterEvent.post

# end of class RegisterEvent
